// manager/pages/calculation/index.js
import { request } from '../../../utils/request';
Page({

    /**
     * 页面的初始数据
     */
    data: {
        activeIndex: 0,
        tabList: [],
        // 字典数据
        dicts: {},
        //个体工商户传参
        merchantId: "",
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {
        if(options.merchantId){
            this.setData({
                merchantId: options.merchantId,
                activeIndex: 1,
            })
        }
        this.getDictionaryInfo("ecard_cust_type");
    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady() {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow() {

    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide() {

    },

    /**
     * 获取客户类型字典
     */
    getDictionaryInfo(dictType) {
        request({
            url: "/commonApi/getDictionaryInfo",
            method: "GET",
            data: {
				dictType
			}
        }).then(res => {
            if(res.code == 0){
                if(dictType=="ecard_cust_type"){
                    let tabList = [];
                    res.data.forEach(item => {
                        // 排除小微企业、新型农业主体
                        if(["3","4"].indexOf(item.dictValue) == -1){
                            item.rulesList = [];
                            tabList.push(item)
                        }
                    })
                    // tabList.map(item => {
                    //     item.rulesList = [];
                    //     return item
                    // })
                    this.setData({
                        tabList
                    })
                    this.getRuleFeatureGroup()
                }else{
                    this.setData({
                        ['dicts.'+dictType]: res.data
                    })
                }
            }
        }).catch(error => {
            // console.log(error)
        })
    },

    /**
     * 获取测算规则组数据
     */
    getRuleFeatureGroup() {
        let { tabList, activeIndex} = this.data;
        if(tabList[activeIndex].rulesList.length>0){
            return
        }
        request({
            url: "/rule/getRuleFeatureGroup",
            reqRSAENCRY: true, // 参数是否加密
            resRSADECRY: true, // 返回值是否解密
            data: { 
                groupCode: tabList[activeIndex].remark
            }
        }).then(res => {
            console.log(res)
            if(res.code == 0){
                tabList[activeIndex].rulesList = res.data;
                res.data.forEach(item => {
                    if(item.enumValue){
                        this.getDictionaryInfo(item.enumValue);
                    } 
                });
                this.setData({
                    tabList
                })
            }
        }).catch(error => {
            // console.log(error)
        })
    },

    
    /**
     * 客户类型事件
     */
    beTypeAt(e) {
        let { index } =  e.currentTarget.dataset;
        if(!this.data.merchantId){
            this.setData({
                activeIndex: index,
            })
            this.getRuleFeatureGroup()
        }
    },

    /**
     * 输入框输入时
     */
    input(e){
        let index = e.target.dataset.index;
        let { tabList, activeIndex } = this.data;
        tabList[activeIndex].rulesList[index].elementsValue = e.detail.value;
        this.setData({
            tabList
        })
    },

    /**
     * 单选框变化时
     */
    radioChange(e){
        console.log(e)
        let { index } = e.currentTarget.dataset;
        let { tabList, activeIndex } = this.data;
        tabList[activeIndex].rulesList[index].elementsValue = e.detail;
        this.setData({
            tabList
        })
    },


    animateNumber(number, duration) {
        let { tabList, activeIndex } = this.data;
        let that = this;
        if(number>0){
            
            let step = duration / 10;
            let count = 0;
            let animation = wx.createAnimation({
                duration: duration,
                timingFunction: "linear",
            });
            tabList[activeIndex].limit = 0;
            that.setData({ 
                animationData: animation.export(),
                tabList
            });
            clearInterval(that.data.timer);
            let timer = setInterval(function () {
                count++;
                if (count > step) {
                    tabList[activeIndex].limit = number;
                    that.setData({ 
                        tabList
                    });
                    clearInterval(that.data.timer);
                    return;
                }
                let newNumber = Math.ceil(number * (count / step));
                tabList[activeIndex].limit = newNumber;
                that.setData({ 
                    tabList
                });
            }, 10);
    
            animation
            .top("-60rpx")
            .step()
            .top("0")
            .step({ duration: 0 });
            that.setData({
                animationData: animation.export(),
            });
            that.setData({ timer: timer });
        }else{
            tabList[activeIndex].limit = 0;
            that.setData({ 
                tabList
            });
        }
    },
    
    // 额度测算
    next(){
        let { tabList, activeIndex } = this.data;
        let msg = this.checkRulesList();
        if(msg){
            wx.showToast({
                title: `${msg}`,
                icon: 'none',
                duration: 2000
            })
            return
        }
        if(tabList[activeIndex].rulesList.length == 0){
            return
        }
        request({
            url: "/rule/getRuleTestOutcome",
            reqRSAENCRY: true, // 参数是否加密
            resRSADECRY: false, // 返回值是否解密
            data: {
                groupId: tabList[activeIndex].rulesList[0].groupId,
                ruleElementsItems: tabList[activeIndex].rulesList
            }
        }).then(res => {
            if(res.code == 0){
                this.animateNumber(res.data, 500);
            }
        }).catch(error => {
            // console.log(error)
        })
    },
    // 生成预授信卡
    toCredit(){
        let { tabList, activeIndex, merchantId } = this.data;
        if(activeIndex == 0){
            wx.navigateTo({
              url: `/manager/pages/personalcredit/index?custType=${tabList[activeIndex].dictValue}&carditLimit=${tabList[activeIndex].limit}`,
            })
        }
        if(activeIndex == 1){
            if(merchantId){
                wx.navigateTo({
                    url: `/manager/pages/merchantcredit/index?custType=${tabList[activeIndex].dictValue}&carditLimit=${tabList[activeIndex].limit}&merchantId=${merchantId}`,
                })
            }else{
                // wx.showModal({
                //     title: `提示`,
                //     content: `请前往'云商圈'进行预授信操作。`,
                //     success (res) {
                //         if (res.confirm) {
                //             console.log('用户点击确定')
                //             wx.navigateTo
                //         } else if (res.cancel) {
                //             console.log('用户点击取消')
                //         }
                //     }   
                // })
                wx.showToast({
                    title: `请前往'云商圈'进行预授信操作。`,
                    icon: 'none',
                    duration: 2000
                })
            }
        }
    },
    /** 验证 */
    checkRulesList() {
        let { tabList, activeIndex } = this.data;
        let rulesList = tabList[activeIndex].rulesList;
        for(let i = 0;i < rulesList.length; i++){
            if(rulesList[i].isEnum=='T'){
                if(rulesList[i].elementsValue){
                    
                }else{
                    return `请选择${rulesList[i].elementsName}`
                }
            }else{
                if(rulesList[i].elementsValue){
                    if (/^\d+$/.test(rulesList[i].elementsValue)) {
                        
                    } else {
                        return `${rulesList[i].elementsName}为整数`
                    }
                }else{
                    return `请输入${rulesList[i].elementsName}`
                }
            }
        }
    },
    
    /*
     * 生命周期函数--监听页面卸载
     */
    onUnload() {

    },

})